#pragma once

#include <iostream>
#include <string>
#include "Log.hpp"
#include "InetAddr.hpp"
#include <unordered_map>
using namespace std;

const string dictpath = "dictionary.txt";
const string sep=":";

using namespace LogModule;

class Dict
{
public:
    Dict(const string& path=dictpath)
        :_dict_path(path)
    {}
    bool LoadDict()
    {
        ifstream in(_dict_path);
        if(!in.is_open())
        {
            cout<<"open dict file error"<<endl;
            return false;
        }
        string line;
        while(getline(in,line))
        {
            auto pos=line.find(sep);
            if(pos==string::npos)
            {
                LOG(LogLevel::WARNING)<<"dict file format error";
                continue;
            }
            string english=line.substr(0,pos);
            string chinese=line.substr(pos+sep.size());
            if(english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING)<<"dict file format error";
                continue;
            }
            _dict.insert(make_pair(english,chinese));
            LOG(LogLevel::DEBUG)<<"加载:"<<line;
        }
        in.close();
        return true;
    }
    string Translate(const string& word,InetAddr &client)
    {
        auto iter=_dict.find(word);
        if(iter==_dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->None";
            return "None";
        }
        LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->" << iter->second;
        return iter->second;    
    }
private:
    string _dict_path;
    unordered_map<string,string> _dict;
};

